import { _decorator, Component, Node, UITransform, view, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('NodeLayoutTool')
export class NodeLayoutTool extends Component {

    @property(Node)
    topNode: Node | null = null;

    @property(Node)
    downNode: Node | null = null;

    @property([Node])
    midNodes: Node[] = [];


    @property(Node)
    touchMgr: Node = null;
    @property(Node)
    gridPanel: Node = null;

    start() {
        this.layoutMidNodes();
        this.touchMgr.setPosition(this.gridPanel.getPosition());
    }

    layoutMidNodes() {
        if (!this.topNode || !this.downNode || this.midNodes.length === 0) {
            console.warn('Please assign topNode, downNode, and midNodes properly.');
            return;
        }

        // 获取屏幕高度
        const screenHeight = view.getVisibleSize().height;

        // 获取顶部和底部节点的世界坐标
        const topNodeWorldPos = this.topNode.getWorldPosition();
        const downNodeWorldPos = this.downNode.getWorldPosition();

        // 计算中间可用空间的高度
        const availableHeight = topNodeWorldPos.y - downNodeWorldPos.y;

        // 检查中间节点的高度总和
        let totalMidNodesHeight = 0;
        this.midNodes.forEach(node => {
            const midNodeHeight = node.getComponent(UITransform)?.height || 0;
            totalMidNodesHeight += midNodeHeight;
        });

        // 计算剩余空间的高度和每个节点之间的间距
        const remainingSpace = availableHeight - totalMidNodesHeight;
        const spacing = remainingSpace / (this.midNodes.length + 1);

        // 开始布局中间节点
        let currentY = topNodeWorldPos.y - spacing;  // 从顶部开始

        this.midNodes.forEach(node => {
            const midNodeHeight = node.getComponent(UITransform)?.height || 0;

            // 更新节点位置
            node.setWorldPosition(new Vec3(node.getWorldPosition().x, currentY - midNodeHeight / 2, 0));

            // 计算下一个节点的Y坐标
            currentY -= (midNodeHeight + spacing);
        });
    }
}
